package li.rafa.UrlShortener.server;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.cache.Cache;
import javax.cache.CacheManager;
import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import li.rafa.UrlShortener.shared.ShortUrl;

import com.google.appengine.api.memcache.stdimpl.GCacheFactory;

public class Redirector extends HttpServlet {
	private static Cache cache = null;
	private static final long serialVersionUID = -6693020316276547947L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		try {
			String originalUrl = null;
			String code = req.getPathInfo().substring(1);
			if (cache == null) {
				Map<Integer, Integer> props = new HashMap<Integer, Integer>();
				props.put(GCacheFactory.EXPIRATION_DELTA, 86400);
				cache = CacheManager.getInstance().getCacheFactory().createCache(props);
			}
			originalUrl = (String) cache.get(code);
			if (originalUrl==null) {
				PersistenceManager pm = PMF.getPM();
				Query query = pm.newQuery(ShortUrl.class);
				query.setFilter("code == codeParam");
				query.declareParameters("String codeParam");	
				List<ShortUrl> persistedShortUrls = (List<ShortUrl>) query.execute(code);
				if (persistedShortUrls.size()>0) {
					originalUrl = persistedShortUrls.get(0).getOrginalUrl();
					cache.put(code, originalUrl);
				}
			}
			if (originalUrl!=null) {
				resp.sendRedirect(originalUrl);
			} else {
				resp.sendError(404);
			}
		} catch (Exception e) {
			resp.sendError(500);
		}

	}
}
